/*
 * Copyright (C) 2010 by Lei Shi (sjtushi@gmail.com)
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License, 
 * version 2, or any later versions.
 *
 */
/*
 * Provide some helper functions to xen-lsof and xen-ps.
 */

#include "proc.h"

int getproc_from_guest(addr_t task_addr, proc_t *proc) {
   char *name = NULL;

   if (task_addr == 0) {
      printf("Cannot get guest process information \
	    from NULL address");
      return STATUS_ERROR;
   }

   if (proc == NULL) {
      printf("Cannot get guest process information \
	    to NULL address");
      return STATUS_ERROR;
   }

   name = (char *) (task_addr + PROCESS_NAME_OFFSET - 
	    TASKSTRUCT_TASKS_OFFSET);

   strcpy(proc->command, name);
   
   memcpy(&(proc->pid), 
	 (char *)task_addr + PROCESS_PID_OFFSET - TASKSTRUCT_TASKS_OFFSET, 4);

   return STATUS_SUCCESS;
}

/* TODO: will support more process options*/
void print_proc(proc_t *proc, int mode) {
   if (proc != NULL) {
      if (mode == PRINT_PROC_LSOF_MODE) {
	 printf("\n");
	 printf("Dom:        %d\n", proc->domid);
	 printf("Pid:        %u\n", proc->pid);
	 printf("Command:    \"%s\"\n\n", proc->command);
      } else if (mode == PRINT_PROC_PS_MODE) {
   	 printf("%5d %s\n", proc->pid, proc->command);
      } else {
	 printf("Unknown print mode\n");
      }
   } 
}

/* 
 * TODO: could initialize offset values in xa library here, 
 * when the value in configuration files not set right
 */
int init_xa_instance(xa_instance_t *xai, uint32_t domid) {

   if (xai == NULL || 
	 xa_init_vm_id_strict(domid, xai) == XA_FAILURE) {
      printf("Initialize xai failed.\n");
      return STATUS_ERROR;
   }
   return STATUS_SUCCESS;
}
